//
//  String+Extension.swift
//  HHSwift
//
//  Created by 华宏 on 2019/10/14.
//  Copyright © 2019 huahong. All rights reserved.
//

import Foundation

extension String{
    
    //md5
       func md5() -> String {
           let str = self.cString(using: String.Encoding.utf8)
           let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
           let digestLen = Int(CC_MD5_DIGEST_LENGTH)
           let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
           CC_MD5(str!, strLen, result)
           let hash = NSMutableString()
           for i in 0 ..< digestLen {
               hash.appendFormat("%02x", result[i])
           }
        
           result.deinitialize(count: 0)//?
           
           return String(format: hash as String)
       }
    
     var MD5:String {
            let utf8 = cString(using: .utf8)
            var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
            CC_MD5(utf8, CC_LONG(utf8!.count - 1), &digest)
            return digest.reduce("") { $0 + String(format:"%02X", $1) }
        }
    
    func chineseConvertToPinYin() -> String {
        let py = NSMutableString(string: self)
        //转成拼音
       CFStringTransform(py as CFMutableString, nil, kCFStringTransformMandarinLatin, false)
       //去掉声母
       CFStringTransform(py as CFMutableString, nil, kCFStringTransformStripDiacritics, false)
 
       return py as String
        
    }
    
    
    //正则表达式
    func isMatch(_ rules:String) -> Bool {
          
       let rules = NSPredicate(format: "SELF MATCHES %@", rules)
       return rules.evaluate(with: self)
     }
}
